package com.ruoyi.web.controller.xcx;


import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.WeChatUtils;
import com.ruoyi.system.domain.AOrder;
import com.ruoyi.system.service.AliPayService;
import com.ruoyi.system.service.PayService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/xcx/aliPay")
public class AliController {

    @Autowired
    private AliPayService alipayService;

    @RepeatSubmit
    @PostMapping(value = "/walletPay")
    public AjaxResult walletPay(@RequestBody AOrder aOrder) {
        return AjaxResult.success(alipayService.walletPay(aOrder));
    }

    @PostMapping("/AOrderAliPayCallBack")
    public String AOrderAliPayCallBack(HttpServletRequest request, HttpServletResponse response) throws Exception{
        Map<String, String> map = new HashMap();
        Map<String, String[]> requestParams = request.getParameterMap();
        if (requestParams.isEmpty()) {
            return "failure";
        } else {
            Iterator iter = requestParams.keySet().iterator();
            String type;
            while (iter.hasNext()) {
                type = (String) iter.next();
                String[] values = (String[]) requestParams.get(type);
                String valueStr = "";
                for (int i = 0; i < values.length; ++i) {
                    valueStr = i == values.length - 1 ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                map.put(type, valueStr);
            }
            String tradeStatus = (String) map.get("trade_status");
            if (!tradeStatus.equals("TRADE_SUCCESS") && !tradeStatus.equals("TRADE_FINISHED")) {
                return "failure";
            } else {
                type = map.get("type");
                if(type.equals("1")){
                    alipayService.checkOrderNo((String) map.get("out_trade_no"), (String) map.get("trade_no"));
                }
                return "success";
            }
        }
    }
}
